/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package bill.model.dao;

import bill.model.vo.Customer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import util.DBUtils;

/**
 *
 * @author Administrator
 */
public class CustomerDAO {
    

    public static ArrayList<Customer> getCustomers(Customer c){
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        ArrayList<Customer> customers = new ArrayList<Customer>();
        String id = null;
        if(c != null && c.getId() != null){
            id = "%" + c.getId() + "%";
        }
        String name = null;
        if(c != null && c.getName() != null){
            name = "%" + c.getName() + "%";
        }
        try {            
            con = DBUtils.getDataConnection();
            String sql = "select cCusCode,cCusName from Customer";
            if (c != null) {
                if (id != null) {
                    sql += " where cCusCode like ?";
                } else if (name != null) {
                    sql += " where cCusName like ?";
                }
            }            
            pstmt = con.prepareStatement(sql);
            if(c != null){
                if(id != null){
                    pstmt.setString(1, id);
                }else if(name != null){
                    pstmt.setString(1, name);
                }
            }
            rs = pstmt.executeQuery();
            int num = 0;
            while(rs.next()){
                Customer cus = new Customer(++num,rs.getString(1),rs.getString(2));
                customers.add(cus);
            }            
        } catch (SQLException ex) {
            Logger.getLogger(CustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            DBUtils.closeAll(rs, pstmt, con);
        }
        return customers;
    }
}
